package com.example.zyl.api.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zyl.api.entity.SysUser;
import com.example.zyl.api.entity.dto.SysUserDto;
import com.example.zyl.api.entity.vo.excel.SysUserExcel;
import com.example.zyl.api.mapper.SysUserMapper;
import com.example.zyl.api.service.SysUserService;
import com.example.zyl.common.enums.RedisQueueEnum;
import com.example.zyl.common.model.SaveBatchList;
import com.example.zyl.common.query.page.PageParam;
import com.example.zyl.common.utils.RedisDelayedQueueUtils;
import com.example.zyl.common.utils.RedisUtils;
import com.example.zyl.common.utils.ServletUtils;
import com.example.zyl.common.utils.constant.RedisConstant;
import com.example.zyl.common.utils.excel.ExcelUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.function.Supplier;


/**
 * 用户信息表(SysUser)表服务实现类
 *
 * @author zyl
 * @since 2024-12-02 08:50:13
 */
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserMapper sysUserMapper;

    private final RedisDelayedQueueUtils queueUtils;

    private final RedisUtils redisUtils;


    @Override
    public Supplier<SysUser> queryById(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);

        return () -> sysUser;
    }

    /**
     * 分页查询
     *
     * @param pageParam 筛选条件
     * @return 查询结果
     */
    @Override
    public Page<SysUser> queryByPage(PageParam<SysUser, SysUserDto> pageParam) {
        //获取查询条件
        SysUserDto tableDto = pageParam.getParam();
        //获取分页信息
        Page<SysUser> page = pageParam.getPage();
        //构建查询条件
        QueryWrapper<SysUser> wrapper = tableDto.defaultWrapper();
        //执行查询
        SysUser sysUser = new SysUser();
        return this.sysUserMapper.selectPage(page, wrapper);
    }

    /**
     * 新增数据
     *
     * @param sysUser2 实例对象
     * @return 实例对象
     */
    @Override
    public SysUser insert(SysUser sysUser2) {
//        SaveBatchList<SysUser> saveBatchList = new SaveBatchList();
        List<SysUser> list = new ArrayList<>();
//
        for (int i = 1; i <= 50000; i++) {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(IdWorker.getId());
            sysUser.setUserName("test" + i);
            sysUser.setPassword("123456");
            sysUser.setUserAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            sysUser.setUserPhone("13812345678");
            sysUser.setUserEmail("test" + i + "@qq.com");
            sysUser.setUserSex("0");
            sysUser.setNickName("test" + i);
            sysUser.init();
            list.add(sysUser);
        }
        SaveBatchList<SysUser> saveBatchList = new SaveBatchList<>();
        saveBatchList.setBachList(list);
        saveBatchList.setBachSize(1000);
        saveBatchList.setBachMapperClass(SysUserMapper.class);
        queueUtils.addQueue(saveBatchList, RedisQueueEnum.BACH_SAVE);
//            sysUser.init();
//        boolean insert = CommonHelper.insertBatch(SysUser.class,list);

        return null;
    }

    /**
     * 修改数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public SysUser update(SysUser sysUser) {
        this.sysUserMapper.updateSingle(sysUser);
        return this.queryById(sysUser.getUserId()).get();
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("delFlag", 0);
        map.put("updateTime", new Date());
        map.put("status", 0);
        return this.sysUserMapper.deleteByIdSingle(userId) > 0;
    }

    @Override
    public Object updateLock() {
        String redisKey = RedisConstant.REDIS_KEY_PREFIX.concat("lock");
        int o = (int) redisUtils.get(redisKey);
        ++o;
        return redisUtils.set(redisKey, o);
    }


    @Override
    public void export(PageParam<SysUser, SysUserDto> pageParam) {
        //获取查询条件
        SysUserDto tableDto = pageParam.getParam();
        //获取分页信息
        //Page<SysUser> page = pageParam.getPage();
        //每页页数
        long size = 20000;
        //构建查询条件
        QueryWrapper<SysUser> wrapper = tableDto.defaultWrapper();
        //总数
        Long count = this.sysUserMapper.selectCount(wrapper);
        //总页数
        long totalPage = (count + size - 1) / size;
        //用户数据
        List<SysUser> userList = new ArrayList<>();

        ThreadPoolTaskExecutor threadAsyncExecutor = SpringUtil.getBean("threadAsyncExecutor", ThreadPoolTaskExecutor.class);

        CountDownLatch countDownLatch = new CountDownLatch((int) totalPage);
        for (int i = 1; i <= totalPage; i++) {
            int finalI = i;
            threadAsyncExecutor.execute(() -> {
                Page<SysUser> currentPage = new Page<>(finalI, size);
                Page<SysUser> userPage = this.sysUserMapper.selectPage(currentPage, wrapper);
                userList.addAll(userPage.getRecords());
                countDownLatch.countDown();
            });
        }

        try {
            countDownLatch.await();
            HttpServletResponse response = ServletUtils.getResponse();
            ExcelUtil.writeExcel(response, userList, "用户信息表", "用户信息表", SysUserExcel.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
